﻿using CuaHangLego.DataAccess;
using CuaHangLego.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;

namespace CuaHangLego.Bussiness
{
    public class KhoBSS
    {
        public IList<NhatKySanPham> ListNhatKy { get; private set; }
        private IList<NhatKySanPham> CurrentNhatKy;
        private IList<SanPham> ListSP;

        public KhoBSS()
        {
            CurrentNhatKy = new List<NhatKySanPham>();
        }

        public void UpdateData()
        {
            this.ListNhatKy = NhatKySanPhamDA.Instance.GetAll();
            this.ListSP = SanPhamDA.Instance.GetAll();
        }

        public IList<NhatKySanPham> GetNhatKySP(int MaSP, DateTime ThoiGian1, DateTime ThoiGian2)
        {
            var data = this.ListNhatKy.Where(nk => nk.SanPham.MaSo == MaSP)
                .Where(nk => DateTime.Parse(nk.ThoiGian.ToShortDateString()) >= DateTime.Parse(ThoiGian1.ToShortDateString())
                    && DateTime.Parse(nk.ThoiGian.ToShortDateString()) <= DateTime.Parse(ThoiGian2.ToShortDateString()))
                .OrderByDescending(nk => nk.ThoiGian);
            CurrentNhatKy = data.ToList();
            return CurrentNhatKy;
        }

        public IList<NhatKySanPham> GetNhatKyNgay(DateTime ThoiGian)
        {
            IList<NhatKySanPham> l = new List<NhatKySanPham>();
            var listSP = this.ListNhatKy.OrderBy(nk => nk.SanPham.MaSo).Select(nk => new { sp = nk.SanPham.MaSo }).Distinct();
            foreach (var s in listSP)
            {
                var data = this.ListNhatKy
                    .Where(nk => nk.SanPham.MaSo == s.sp)
                    .Where(nk => DateTime.Parse(nk.ThoiGian.ToShortDateString()) <= DateTime.Parse(ThoiGian.ToShortDateString()))
                    .OrderByDescending(nk => nk.ThoiGian);
                IList<NhatKySanPham> temp = data.ToList();
                if (temp.Count > 0) l.Add(temp.ElementAt(0));
            }
            CurrentNhatKy = l;
            return CurrentNhatKy;
        }

        public IList<NhatKySanPham> GetNhatKyNgayBy(string key, ChuDe cd, int sl1, int sl2)
        {
            var data = this.CurrentNhatKy
                .Where(nk => (nk.TenSanPham.ToLower().Contains(key.ToLower()) 
                    && (nk.SanPham.ChuDe.MaSo == cd.MaSo || cd.MaSo == -1) 
                    && nk.SoLuong >= sl1 && nk.SoLuong <= sl2));
            return data.OrderByDescending(nk => nk.ThoiGian).ToList();
        }
        public IList<NhatKySanPham> GetNhatKyNgayAll()
        {
            return this.CurrentNhatKy.OrderByDescending(nk => nk.ThoiGian).ToList();
        }

        public IList<SanPham> GetAllSanPham()
        {
            return SanPhamDA.Instance.GetAll();
        }

        public IList<SanPham> SearchSanPham(string key, ChuDe cd)
        {
            var data = this.ListSP
                .Where(sp => (sp.Ten.ToLower().Contains(key.ToLower())
                    && (sp.ChuDe.MaSo == cd.MaSo || cd.MaSo == -1)));
            return data.ToList();
        }

        public void Export(IList<NhatKySanPham> nk)
        {
            string dir = "C:";
            FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog();
            DialogResult result = dlg.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.OK)
            {

                dir = dlg.SelectedPath;
                Excel.Application xlApp;
                Excel.Workbook xlWorkBook;
                Excel.Worksheet xlWorkSheet;
                object misValue = System.Reflection.Missing.Value;
                Excel.Range chartRange;
                DateTime date = DateTime.Now;
                string link = "\\NhatKy_" + date.Year.ToString() + date.Month.ToString() + date.Day.ToString() + "_" + date.Hour.ToString() + date.Minute + date.Second + ".xls";

                xlApp = new Excel.Application();

                xlApp.StandardFont = "Arial";
                xlApp.StandardFontSize = 11;
                xlWorkBook = xlApp.Workbooks.Add(misValue);
                xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
                xlWorkSheet.Name = "KHO";

                xlWorkSheet.get_Range("A1", "D1").Merge(false);
                xlWorkSheet.get_Range("A1", "D1").Font.ColorIndex = 43;
                xlWorkSheet.get_Range("A1", "D1").Font.Size = 22;
                xlWorkSheet.Cells[1, 1] = "NHẬT KÝ SẢN PHẨM";

                xlWorkSheet.Cells[2, 1] = "Thời gian";
                xlWorkSheet.Cells[2, 2] = "#" + date.ToString();

                xlWorkSheet.get_Range("A2", "D2").Font.Bold = true;
                xlWorkSheet.get_Range("A2", "D2").Interior.ColorIndex = 43;
                xlWorkSheet.get_Range("A2", "D2").HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                xlWorkSheet.Cells[2, 1] = "STT";
                xlWorkSheet.Cells[2, 2] = "Mã sản phẩm";
                xlWorkSheet.Cells[2, 3] = "Tên sản phẩm";
                xlWorkSheet.Cells[2, 4] = "Số lượng";

                for (int i = 0; i < nk.Count; i++)
                {
                    xlWorkSheet.Cells[i + 3, 1] = i + 1;
                    xlWorkSheet.Cells[i + 3, 2] = nk[i].SanPham.MaSo;
                    xlWorkSheet.Cells[i + 3, 3] = nk[i].SanPham.Ten;
                    xlWorkSheet.Cells[i + 3, 4] = nk[i].SoLuong;
                }
                xlWorkSheet.Cells[nk.Count + 3, 3] = "Tổng cộng";
                xlWorkSheet.Cells[nk.Count + 3, 4] = string.Format("=SUM(D{0}:D{1})", 3, nk.Count + 2);
                xlWorkSheet.Cells[nk.Count + 3, 3].Font.Bold = true;
                xlWorkSheet.Cells[nk.Count + 3, 4].Font.Bold = true;
                chartRange = xlWorkSheet.get_Range("A1", "Z200");
                chartRange.Columns.AutoFit();

                try
                {
                    xlWorkBook.SaveAs(dir + link, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
                }
                catch
                {
                    MessageBox.Show("Không thể lưu file!");
                }
                finally
                {
                    xlWorkBook.Close(true, misValue, misValue);
                    xlApp.Quit();
                }

                releaseObject(xlApp);
                releaseObject(xlWorkBook);
                releaseObject(xlWorkSheet);

                MessageBox.Show("Đã tạo report tại " + dir + link);
            }
        }
        private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Unable to release the Object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        }
    }
}
